<template>
  <div>
    <van-nav-bar title="头条-登录"  left-arrow @click-left="$router.back()" />

    <div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="user.mobile"
          required
          name="mobile"
          label="手机号"
          placeholder="手机号"
          :rules="[{ required: true, message: '请填写正确手机号',pattern: /^1[3-9]\d{9}$/ }]"
          />
        <van-field
        v-model="user.code"
        required
        type="password"
        name="code"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写6位密码',pattern:/^\d{6}$/}]"
        />
        <div style="margin: 16px">
          <van-button round block :loading="isLoading"  type="info" native-type="submit" loading-text="正在登录ing..." :disabled="isLoading">登录</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { loginAPI } from '@/api/index.js'
import { setToken } from '@/utils/token.js'
import { setStorage } from '@/utils/storage.js'
import Notify from '@/ui/Notify.js'

export default {
  name: 'login',
  data () {
    return {
      user: {
        mobile: '13812345678', // 手机号
        code: '246810'// 密码
      },
      isLoading: false// 登录按钮的加载状态
    }
  },
  methods: {
    async onSubmit (values) {
      // 可以直接用values收集参数名和值
      this.isLoading = !this.isLoading

      try {
        const { data: res } = await loginAPI(values)
        Notify({ type: 'success', message: '登录成功' })
        setToken(res.data.token)
        setStorage('refresh_token', res.data.refresh_token)
        this.$router.replace({
          path: this.$route.query.path || '/layout/home'
        })
      } catch (err) {
        Notify({ type: 'danger', message: '账号或密码错误' })
      }
      this.isLoading = !this.isLoading
    }
  }
}
</script>

<style lang="less" scoped></style>
